import { LocalHttpFactory } from "./LocalHttpFactory";
import { ILocalHttp } from "./ILocalHttp";
import { LocalHttpProto } from "./LocalHttpProto";

/**
 * 本地服务器
 */
export class LocalHttpServer implements ILocalHttp {



    protected static pushList: net.PushData[] = []

    send(url: string, data: string, callback: (err: string, data: string) => void): void {
        let reqData: net.ReqData = JSON.parse(data)
        // console.log('LocalHttpServer reqData ', reqData)
        let str = url.replace(/http[s]:\/\//, '')
        let list = str.split('/')
        //先判断url中是否包含类名和函数名，这是一种用法，也可以将类名和函数名都放到发送的数据中。
        let className: string = ''
        let functionName: string = ''
        if (list[1]) {
            className = list[1]
        }
        if (list[2])
            functionName = list[2]

        if (className && functionName) {
            let ins: LocalHttpProto = LocalHttpFactory.builder(className)
            if (ins && ins[functionName]) {
                ins.setService(this)
                ins[functionName](reqData, (param: any) => {
                    callback(null, JSON.stringify(param))
                })
            }
        } else {
            let ins: LocalHttpProto = LocalHttpFactory.builder(className)
            if (ins) {
                ins.setService(this)
                ins.action(reqData.data, (code: number, resData: any) => {
                    let result: net.ResData = { code: code, data: resData, session: reqData.session, protoId: reqData.protoId }
                    result.push = LocalHttpServer.pushList;
                    callback(null, JSON.stringify(result));
                    if (LocalHttpServer.pushList.length > 0) {
                        LocalHttpServer.pushList.length = 0;
                    }
                })


            } else {
                callback('ins is null class is ', null)

            }
        }

    }

    push(pushName: string, pushData: any): void {
        let data: net.PushData = {
            protoId: pushName,
            data: pushData
        }

        LocalHttpServer.pushList.push(data)
    }
}